#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""FTP2PDM 系统图形用户界面
用于执行Excel文件处理、文件搜索复制、压缩和解压等功能的可视化界面
"""

import tkinter as tk
from tkinter import ttk, filedialog, messagebox, scrolledtext
import os
import sys
import threading
import traceback

# 添加当前目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# 导入主程序模块
from main import FTP2PDM

class FTP2PDMGUI:
    def __init__(self, root):
        """初始化FTP2PDM图形用户界面"""
        self.root = root
        self.root.title("FTP2PDM 系统")
        self.root.geometry("1000x700")
        self.root.minsize(800, 600)
        
        # 创建主程序实例
        self.ftp2pdm = FTP2PDM()
        
        # 创建选项卡控件
        self.notebook = ttk.Notebook(self.root)
        self.notebook.pack(fill="both", expand=True, padx=10, pady=10)
        
        # 创建各个功能选项卡
        self.create_excel_tab()
        self.create_clipboard_tab()
        self.create_file_tab()
        self.create_search_copy_tab()
        
        # 创建日志显示区域
        self.create_log_area()
        
        # 设置中文显示支持
        self._setup_chinese_support()
        
        # 初始化日志
        self.log("FTP2PDM 系统已启动")
    
    def _setup_chinese_support(self):
        """设置中文显示支持，添加字体回退机制"""
        # 尝试使用多种中文字体作为备选
        chinese_fonts = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC", "Arial Unicode MS", "Microsoft YaHei"]
        
        # 获取可用的字体
        available_fonts = tk.font.families()
        
        # 选择一个可用的中文字体
        selected_font = "SimHei"  # 默认字体
        for font in chinese_fonts:
            if font in available_fonts:
                selected_font = font
                break
        
        # 在日志区域创建后再记录日志
        if hasattr(self, 'log_text'):
            self.log(f"使用字体: {selected_font}")
        
        # 设置中文字体支持
        self.style = ttk.Style()
        self.style.configure(
            "TLabel",
            font=(selected_font, 10)
        )
        self.style.configure(
            "TButton",
            font=(selected_font, 10)
        )
        self.style.configure(
            "TEntry",
            font=(selected_font, 10)
        )
        self.style.configure(
            "TText",
            font=(selected_font, 10)
        )
        self.style.configure(
            "TNotebook",
            font=(selected_font, 10)
        )
        self.style.configure(
            "TNotebook.Tab",
            font=(selected_font, 10)
        )
        
        # 设置全局默认字体
        default_font = tk.font.nametofont("TkDefaultFont")
        default_font.configure(family=selected_font, size=10)
        text_font = tk.font.nametofont("TkTextFont")
        text_font.configure(family=selected_font, size=10)
        
        # 设置tkinter的默认编码为UTF-8
        if hasattr(sys.stdout, 'reconfigure'):
            sys.stdout.reconfigure(encoding='utf-8')
        if hasattr(sys.stderr, 'reconfigure'):
            sys.stderr.reconfigure(encoding='utf-8')
            
    def create_excel_tab(self):
        """创建Excel操作选项卡"""
        excel_tab = ttk.Frame(self.notebook)
        self.notebook.add(excel_tab, text="Excel操作")
        
        # 创建网格布局
        excel_tab.grid_columnconfigure(0, weight=1)
        excel_tab.grid_columnconfigure(1, weight=3)
        excel_tab.grid_columnconfigure(2, weight=1)
        
        # 文件路径选择
        ttk.Label(excel_tab, text="Excel文件路径:", anchor="e").grid(row=0, column=0, padx=10, pady=10, sticky="ew")
        self.excel_file_path = ttk.Entry(excel_tab)
        self.excel_file_path.grid(row=0, column=1, padx=10, pady=10, sticky="ew")
        ttk.Button(excel_tab, text="浏览...", command=self.browse_excel_file).grid(row=0, column=2, padx=10, pady=10)
        
        # 搜索关键词
        ttk.Label(excel_tab, text="搜索关键词:", anchor="e").grid(row=1, column=0, padx=10, pady=10, sticky="ew")
        self.excel_search_term = ttk.Entry(excel_tab)
        self.excel_search_term.grid(row=1, column=1, padx=10, pady=10, sticky="ew")
        
        # 按钮区域
        button_frame = ttk.Frame(excel_tab)
        button_frame.grid(row=2, column=0, columnspan=3, pady=10)
        
        ttk.Button(button_frame, text="读取Excel", command=lambda: self.run_in_thread(self.read_excel)).pack(side="left", padx=5)
        ttk.Button(button_frame, text="格式化Excel", command=lambda: self.run_in_thread(self.format_excel)).pack(side="left", padx=5)
        ttk.Button(button_frame, text="搜索Excel内容", command=lambda: self.run_in_thread(self.search_in_excel)).pack(side="left", padx=5)
        
        # 结果显示区域
        ttk.Label(excel_tab, text="Excel内容预览:", anchor="w").grid(row=3, column=0, columnspan=3, padx=10, pady=5, sticky="w")
        self.excel_result_text = scrolledtext.ScrolledText(excel_tab, height=15, wrap=tk.WORD)
        self.excel_result_text.grid(row=4, column=0, columnspan=3, padx=10, pady=5, sticky="nsew")
        excel_tab.grid_rowconfigure(4, weight=1)
    
    def create_clipboard_tab(self):
        """创建剪贴板操作选项卡"""
        clipboard_tab = ttk.Frame(self.notebook)
        self.notebook.add(clipboard_tab, text="剪贴板操作")
        
        # 按钮区域
        button_frame = ttk.Frame(clipboard_tab)
        button_frame.pack(pady=20)
        
        ttk.Button(button_frame, text="获取剪贴板内容", command=lambda: self.run_in_thread(self.get_clipboard_content)).pack(side="left", padx=10, pady=10)
        ttk.Button(button_frame, text="从Excel复制单元格(表格格式)", command=lambda: self.run_in_thread(self.copy_excel_selected_cells)).pack(side="left", padx=10, pady=10)
        ttk.Button(button_frame, text="从Excel复制单元格(列表格式)", command=lambda: self.run_in_thread(self.copy_excel_selected_cells_as_list)).pack(side="left", padx=10, pady=10)
        
        # 剪贴板内容显示
        ttk.Label(clipboard_tab, text="剪贴板内容:", anchor="w").pack(fill="x", padx=10, pady=5)
        self.clipboard_text = scrolledtext.ScrolledText(clipboard_tab, height=20, wrap=tk.WORD)
        self.clipboard_text.pack(fill="both", expand=True, padx=10, pady=5)
    
    def create_file_tab(self):
        """创建文件操作选项卡"""
        file_tab = ttk.Frame(self.notebook)
        self.notebook.add(file_tab, text="文件操作")
        
        # 搜索目录
        ttk.Label(file_tab, text="搜索目录:", anchor="e").grid(row=0, column=0, padx=10, pady=10, sticky="ew")
        self.search_dir = ttk.Entry(file_tab)
        self.search_dir.grid(row=0, column=1, padx=10, pady=10, sticky="ew")
        ttk.Button(file_tab, text="浏览...", command=self.browse_search_dir).grid(row=0, column=2, padx=10, pady=10)
        
        # 搜索关键词
        ttk.Label(file_tab, text="搜索关键词(用逗号分隔):", anchor="e").grid(row=1, column=0, padx=10, pady=10, sticky="ew")
        self.file_search_terms = ttk.Entry(file_tab)
        self.file_search_terms.grid(row=1, column=1, padx=10, pady=10, sticky="ew")
        
        # 目标目录
        ttk.Label(file_tab, text="目标目录:", anchor="e").grid(row=2, column=0, padx=10, pady=10, sticky="ew")
        self.target_dir = ttk.Entry(file_tab)
        self.target_dir.grid(row=2, column=1, padx=10, pady=10, sticky="ew")
        ttk.Button(file_tab, text="浏览...", command=self.browse_target_dir).grid(row=2, column=2, padx=10, pady=10)
        
        # 压缩文件路径
        ttk.Label(file_tab, text="压缩文件路径:", anchor="e").grid(row=3, column=0, padx=10, pady=10, sticky="ew")
        self.zip_file_path = ttk.Entry(file_tab)
        self.zip_file_path.grid(row=3, column=1, padx=10, pady=10, sticky="ew")
        ttk.Button(file_tab, text="浏览...", command=self.browse_zip_file).grid(row=3, column=2, padx=10, pady=10)
        
        # 按钮区域
        button_frame = ttk.Frame(file_tab)
        button_frame.grid(row=4, column=0, columnspan=3, pady=10)
        
        ttk.Button(button_frame, text="搜索文件", command=lambda: self.run_in_thread(self.search_files)).pack(side="left", padx=5)
        ttk.Button(button_frame, text="复制文件", command=lambda: self.run_in_thread(self.copy_files)).pack(side="left", padx=5)
        ttk.Button(button_frame, text="压缩文件", command=lambda: self.run_in_thread(self.zip_files)).pack(side="left", padx=5)
        ttk.Button(button_frame, text="删除文件", command=lambda: self.run_in_thread(self.delete_files)).pack(side="left", padx=5)
        
        # 搜索结果显示
        ttk.Label(file_tab, text="搜索结果:", anchor="w").grid(row=5, column=0, columnspan=3, padx=10, pady=5, sticky="w")
        self.search_result_listbox = tk.Listbox(file_tab, selectmode=tk.EXTENDED, height=10)
        self.search_result_listbox.grid(row=6, column=0, columnspan=3, padx=10, pady=5, sticky="nsew")
        scrollbar = ttk.Scrollbar(self.search_result_listbox, orient="vertical", command=self.search_result_listbox.yview)
        scrollbar.pack(side="right", fill="y")
        self.search_result_listbox.config(yscrollcommand=scrollbar.set)
        
        # 设置权重使列表框自适应
        file_tab.grid_rowconfigure(6, weight=1)
        file_tab.grid_columnconfigure(1, weight=1)
    
    def create_search_copy_tab(self):
        """创建文件搜索与智能复制选项卡"""
        search_copy_tab = ttk.Frame(self.notebook)
        self.notebook.add(search_copy_tab, text="文件搜索与智能复制")
        
        # 搜索路径
        ttk.Label(search_copy_tab, text="搜索路径:", anchor="e").grid(row=0, column=0, padx=10, pady=10, sticky="ew")
        self.smart_search_path = ttk.Entry(search_copy_tab)
        self.smart_search_path.grid(row=0, column=1, padx=10, pady=10, sticky="ew")
        ttk.Button(search_copy_tab, text="浏览...", command=self.browse_smart_search_path).grid(row=0, column=2, padx=10, pady=10)
        
        # 目标路径
        ttk.Label(search_copy_tab, text="目标路径:", anchor="e").grid(row=1, column=0, padx=10, pady=10, sticky="ew")
        self.smart_target_path = ttk.Entry(search_copy_tab)
        self.smart_target_path.grid(row=1, column=1, padx=10, pady=10, sticky="ew")
        ttk.Button(search_copy_tab, text="浏览...", command=self.browse_smart_target_path).grid(row=1, column=2, padx=10, pady=10)
        
        # 搜索模式输入
        ttk.Label(search_copy_tab, text="搜索模式(用逗号分隔，留空则从剪贴板获取):", anchor="e").grid(row=2, column=0, padx=10, pady=10, sticky="ew")
        self.smart_search_patterns = ttk.Entry(search_copy_tab)
        self.smart_search_patterns.grid(row=2, column=1, padx=10, pady=10, sticky="ew")
        
        # 选项设置
        option_frame = ttk.Frame(search_copy_tab)
        option_frame.grid(row=3, column=0, columnspan=3, pady=10)
        
        self.recursive_var = tk.BooleanVar(value=True)
        self.overwrite_var = tk.BooleanVar(value=False)
        
        ttk.Checkbutton(option_frame, text="递归搜索子目录", variable=self.recursive_var).pack(side="left", padx=10)
        ttk.Checkbutton(option_frame, text="覆盖已存在的文件", variable=self.overwrite_var).pack(side="left", padx=10)
        
        # 按钮区域
        button_frame = ttk.Frame(search_copy_tab)
        button_frame.grid(row=4, column=0, columnspan=3, pady=10)
        
        ttk.Button(button_frame, text="一站式处理(剪贴板->搜索->复制)", command=lambda: self.run_in_thread(self.search_and_copy_files_from_clipboard)).pack(side="left", padx=5)
        ttk.Button(button_frame, text="搜索文件", command=lambda: self.run_in_thread(self.search_files_with_manager)).pack(side="left", padx=5)
        ttk.Button(button_frame, text="复制文件", command=lambda: self.run_in_thread(self.copy_items_with_manager)).pack(side="left", padx=5)
        
        # 搜索结果显示
        ttk.Label(search_copy_tab, text="搜索结果:", anchor="w").grid(row=5, column=0, columnspan=3, padx=10, pady=5, sticky="w")
        self.smart_search_result_listbox = tk.Listbox(search_copy_tab, selectmode=tk.EXTENDED, height=10)
        self.smart_search_result_listbox.grid(row=6, column=0, columnspan=3, padx=10, pady=5, sticky="nsew")
        scrollbar = ttk.Scrollbar(self.smart_search_result_listbox, orient="vertical", command=self.smart_search_result_listbox.yview)
        scrollbar.pack(side="right", fill="y")
        self.smart_search_result_listbox.config(yscrollcommand=scrollbar.set)
        
        # 设置权重使列表框自适应
        search_copy_tab.grid_rowconfigure(6, weight=1)
        search_copy_tab.grid_columnconfigure(1, weight=1)
    
    def create_log_area(self):
        """创建日志显示区域"""
        log_frame = ttk.LabelFrame(self.root, text="日志信息")
        log_frame.pack(fill="both", expand=True, padx=10, pady=10)
        
        self.log_text = scrolledtext.ScrolledText(log_frame, height=10, wrap=tk.WORD)
        self.log_text.pack(fill="both", expand=True, padx=5, pady=5)
        self.log_text.config(state=tk.DISABLED)
    
    def browse_excel_file(self):
        """浏览选择Excel文件"""
        file_path = filedialog.askopenfilename(
            title="选择Excel文件",
            filetypes=[("Excel文件", "*.xlsx;*.xls")]
        )
        if file_path:
            self.excel_file_path.delete(0, tk.END)
            self.excel_file_path.insert(0, file_path)
    
    def browse_search_dir(self):
        """浏览选择搜索目录"""
        dir_path = filedialog.askdirectory(title="选择搜索目录")
        if dir_path:
            self.search_dir.delete(0, tk.END)
            self.search_dir.insert(0, dir_path)
    
    def browse_target_dir(self):
        """浏览选择目标目录"""
        dir_path = filedialog.askdirectory(title="选择目标目录")
        if dir_path:
            self.target_dir.delete(0, tk.END)
            self.target_dir.insert(0, dir_path)
    
    def browse_zip_file(self):
        """浏览选择压缩文件路径"""
        file_path = filedialog.asksaveasfilename(
            title="保存压缩文件",
            defaultextension=".zip",
            filetypes=[("ZIP文件", "*.zip")]
        )
        if file_path:
            self.zip_file_path.delete(0, tk.END)
            self.zip_file_path.insert(0, file_path)
    
    def browse_smart_search_path(self):
        """浏览选择智能搜索路径"""
        dir_path = filedialog.askdirectory(title="选择搜索路径")
        if dir_path:
            self.smart_search_path.delete(0, tk.END)
            self.smart_search_path.insert(0, dir_path)
    
    def browse_smart_target_path(self):
        """浏览选择智能目标路径"""
        dir_path = filedialog.askdirectory(title="选择目标路径")
        if dir_path:
            self.smart_target_path.delete(0, tk.END)
            self.smart_target_path.insert(0, dir_path)
    
    def log(self, message):
        """在日志区域显示消息，确保UTF-8编码正确处理"""
        # 确保消息是UTF-8编码的字符串
        try:
            if isinstance(message, bytes):
                message = message.decode('utf-8')
            elif not isinstance(message, str):
                message = str(message)
        except Exception as e:
            message = f"日志编码错误: {str(e)}"
        
        self.log_text.config(state=tk.NORMAL)
        self.log_text.insert(tk.END, message + "\n")
        self.log_text.see(tk.END)
        self.log_text.config(state=tk.DISABLED)
    
    def run_in_thread(self, func):
        """在新线程中运行函数，避免界面卡顿"""
        thread = threading.Thread(target=self.run_with_exception_handling, args=(func,))
        thread.daemon = True
        thread.start()
    
    def run_with_exception_handling(self, func):
        """运行函数并处理异常"""
        try:
            func()
        except Exception as e:
            self.log(f"错误: {str(e)}")
            self.log(f"详细错误信息:\n{traceback.format_exc()}")
            messagebox.showerror("错误", f"执行过程中发生错误:\n{str(e)}")
    
    # Excel操作相关方法
    def read_excel(self):
        """读取Excel文件"""
        file_path = self.excel_file_path.get().strip()
        if not file_path:
            messagebox.showwarning("警告", "请选择Excel文件")
            return
        
        if not os.path.exists(file_path):
            messagebox.showwarning("警告", "文件不存在")
            return
        
        self.log(f"开始读取Excel文件: {file_path}")
        df = self.ftp2pdm.read_excel(file_path)
        if df is not None:
            self.log(f"成功读取Excel文件，共{len(df)}行数据")
            # 显示前10行数据作为预览
            preview_text = str(df.head(10))
            self.excel_result_text.delete(1.0, tk.END)
            self.excel_result_text.insert(tk.END, preview_text)
        else:
            self.log("读取Excel文件失败")
    
    def format_excel(self):
        """格式化Excel文件"""
        file_path = self.excel_file_path.get().strip()
        if not file_path:
            messagebox.showwarning("警告", "请选择Excel文件")
            return
        
        if not os.path.exists(file_path):
            messagebox.showwarning("警告", "文件不存在")
            return
        
        self.log(f"开始格式化Excel文件: {file_path}")
        self.ftp2pdm.format_excel(file_path)
        self.log("Excel文件格式化完成")
    
    def search_in_excel(self):
        """在Excel文件中搜索内容"""
        file_path = self.excel_file_path.get().strip()
        search_term = self.excel_search_term.get().strip()
        
        if not file_path:
            messagebox.showwarning("警告", "请选择Excel文件")
            return
        
        if not search_term:
            messagebox.showwarning("警告", "请输入搜索关键词")
            return
        
        if not os.path.exists(file_path):
            messagebox.showwarning("警告", "文件不存在")
            return
        
        self.log(f"在Excel文件中搜索关键词 '{search_term}'")
        result = self.ftp2pdm.search_in_excel(file_path, search_term)
        if result is not None and not result.empty:
            self.log(f"找到{len(result)}条匹配记录")
            self.excel_result_text.delete(1.0, tk.END)
            self.excel_result_text.insert(tk.END, str(result))
        else:
            self.log(f"没有找到匹配关键词 '{search_term}' 的记录")
            self.excel_result_text.delete(1.0, tk.END)
            self.excel_result_text.insert(tk.END, "没有找到匹配的记录")
    
    # 剪贴板操作相关方法
    def get_clipboard_content(self):
        """获取剪贴板内容"""
        self.log("获取剪贴板内容")
        content = self.ftp2pdm.get_clipboard_content()
        if content:
            self.log(f"成功获取剪贴板内容，长度: {len(content)} 字符")
            self.clipboard_text.delete(1.0, tk.END)
            self.clipboard_text.insert(tk.END, content)
        else:
            self.log("剪贴板为空或获取失败")
            self.clipboard_text.delete(1.0, tk.END)
            self.clipboard_text.insert(tk.END, "剪贴板为空或获取失败")
    
    def copy_excel_selected_cells(self):
        """从Excel复制单元格(表格格式)"""
        self.log("尝试从Excel复制选中的单元格(表格格式)")
        success = self.ftp2pdm.copy_excel_selected_cells()
        if success:
            self.log("成功将Excel选中的单元格以表格格式复制到剪贴板")
            messagebox.showinfo("成功", "已将Excel选中的单元格以表格格式复制到剪贴板")
        else:
            self.log("从Excel复制单元格失败，请确保Excel已打开并选中了单元格")
            messagebox.showwarning("警告", "从Excel复制单元格失败，请确保Excel已打开并选中了单元格")
    
    def copy_excel_selected_cells_as_list(self):
        """从Excel复制单元格(列表格式)"""
        self.log("尝试从Excel复制选中的单元格(列表格式)")
        success = self.ftp2pdm.copy_excel_selected_cells_as_list()
        if success:
            self.log("成功将Excel选中的单元格以列表格式复制到剪贴板")
            messagebox.showinfo("成功", "已将Excel选中的单元格以列表格式复制到剪贴板")
        else:
            self.log("从Excel复制单元格失败，请确保Excel已打开并选中了单元格")
            messagebox.showwarning("警告", "从Excel复制单元格失败，请确保Excel已打开并选中了单元格")
    
    # 文件操作相关方法
    def search_files(self):
        """搜索文件"""
        search_dir = self.search_dir.get().strip()
        search_terms_text = self.file_search_terms.get().strip()
        
        if not search_dir:
            messagebox.showwarning("警告", "请选择搜索目录")
            return
        
        if not search_terms_text:
            messagebox.showwarning("警告", "请输入搜索关键词")
            return
        
        if not os.path.exists(search_dir):
            messagebox.showwarning("警告", "搜索目录不存在")
            return
        
        # 分割搜索关键词
        search_terms = [term.strip() for term in search_terms_text.split(',') if term.strip()]
        
        self.log(f"在目录 '{search_dir}' 中搜索关键词: {', '.join(search_terms)}")
        found_files = self.ftp2pdm.search_files(search_dir, search_terms)
        
        # 清空列表框并添加搜索结果
        self.search_result_listbox.delete(0, tk.END)
        for file_path in found_files:
            self.search_result_listbox.insert(tk.END, file_path)
        
        self.log(f"搜索完成，共找到{len(found_files)}个匹配文件")
    
    def copy_files(self):
        """复制文件"""
        target_dir = self.target_dir.get().strip()
        selected_indices = self.search_result_listbox.curselection()
        
        if not target_dir:
            messagebox.showwarning("警告", "请选择目标目录")
            return
        
        if not selected_indices:
            messagebox.showwarning("警告", "请从搜索结果中选择要复制的文件")
            return
        
        # 创建目标目录（如果不存在）
        if not os.path.exists(target_dir):
            os.makedirs(target_dir)
            self.log(f"创建目标目录: {target_dir}")
        
        # 获取选中的文件路径
        selected_files = [self.search_result_listbox.get(i) for i in selected_indices]
        
        self.log(f"开始复制{len(selected_files)}个文件到 '{target_dir}'")
        self.ftp2pdm.copy_files(selected_files, target_dir)
        self.log("文件复制完成")
        messagebox.showinfo("成功", f"已成功复制{len(selected_files)}个文件")
    
    def zip_files(self):
        """压缩文件"""
        zip_path = self.zip_file_path.get().strip()
        selected_indices = self.search_result_listbox.curselection()
        
        if not zip_path:
            messagebox.showwarning("警告", "请选择压缩文件保存路径")
            return
        
        if not selected_indices:
            messagebox.showwarning("警告", "请从搜索结果中选择要压缩的文件")
            return
        
        # 获取选中的文件路径
        selected_files = [self.search_result_listbox.get(i) for i in selected_indices]
        
        self.log(f"开始压缩{len(selected_files)}个文件到 '{zip_path}'")
        self.ftp2pdm.zip_files(selected_files, zip_path)
        self.log("文件压缩完成")
        messagebox.showinfo("成功", f"已成功压缩{len(selected_files)}个文件")
    
    def delete_files(self):
        """删除文件"""
        selected_indices = self.search_result_listbox.curselection()
        
        if not selected_indices:
            messagebox.showwarning("警告", "请从搜索结果中选择要删除的文件")
            return
        
        # 获取选中的文件路径
        selected_files = [self.search_result_listbox.get(i) for i in selected_indices]
        
        # 确认删除
        if not messagebox.askyesno("确认删除", f"确定要删除选中的{len(selected_files)}个文件吗？\n此操作不可恢复！"):
            return
        
        self.log(f"开始删除{len(selected_files)}个文件")
        self.ftp2pdm.delete_files(selected_files)
        self.log("文件删除完成")
        
        # 从列表框中移除已删除的文件
        for i in sorted(selected_indices, reverse=True):
            self.search_result_listbox.delete(i)
        
        messagebox.showinfo("成功", f"已成功删除{len(selected_files)}个文件")
    
    # 文件搜索与智能复制相关方法
    def search_and_copy_files_from_clipboard(self):
        """一站式处理(剪贴板->搜索->复制)"""
        search_path = self.smart_search_path.get().strip()
        target_path = self.smart_target_path.get().strip()
        recursive = self.recursive_var.get()
        overwrite = self.overwrite_var.get()
        
        if not search_path:
            messagebox.showwarning("警告", "请选择搜索路径")
            return
        
        if not target_path:
            messagebox.showwarning("警告", "请选择目标路径")
            return
        
        if not os.path.exists(search_path):
            messagebox.showwarning("警告", "搜索路径不存在")
            return
        
        self.log(f"一站式处理: 从剪贴板读取值，在 '{search_path}' 中搜索并复制到 '{target_path}'")
        success, count = self.ftp2pdm.search_and_copy_files_from_clipboard(
            search_path, target_path, recursive, overwrite
        )
        
        if success:
            self.log(f"一站式处理完成，成功复制了{count}个文件/文件夹")
            messagebox.showinfo("成功", f"一站式处理完成，成功复制了{count}个文件/文件夹")
        else:
            self.log("一站式处理失败或没有找到匹配的文件")
            messagebox.showwarning("警告", "一站式处理失败或没有找到匹配的文件")
    
    def search_files_with_manager(self):
        """搜索文件(使用文件搜索管理器)"""
        search_path = self.smart_search_path.get().strip()
        search_patterns_text = self.smart_search_patterns.get().strip()
        recursive = self.recursive_var.get()
        
        if not search_path:
            messagebox.showwarning("警告", "请选择搜索路径")
            return
        
        if not os.path.exists(search_path):
            messagebox.showwarning("警告", "搜索路径不存在")
            return
        
        # 准备搜索模式
        search_patterns = None
        if search_patterns_text:
            search_patterns = [pattern.strip() for pattern in search_patterns_text.split(',') if pattern.strip()]
            self.log(f"使用指定的搜索模式: {', '.join(search_patterns)}")
        else:
            self.log("从剪贴板获取搜索模式")
        
        self.log(f"在目录 '{search_path}' 中搜索文件")
        found_files = self.ftp2pdm.search_files_with_manager(search_path, search_patterns, recursive)
        
        # 清空列表框并添加搜索结果
        self.smart_search_result_listbox.delete(0, tk.END)
        for file_path in found_files:
            self.smart_search_result_listbox.insert(tk.END, file_path)
        
        self.log(f"搜索完成，共找到{len(found_files)}个匹配文件/文件夹")
    
    def copy_items_with_manager(self):
        """复制文件(使用文件搜索管理器)"""
        target_path = self.smart_target_path.get().strip()
        selected_indices = self.smart_search_result_listbox.curselection()
        overwrite = self.overwrite_var.get()
        
        if not target_path:
            messagebox.showwarning("警告", "请选择目标路径")
            return
        
        if not selected_indices:
            messagebox.showwarning("警告", "请从搜索结果中选择要复制的文件/文件夹")
            return
        
        # 创建目标目录（如果不存在）
        if not os.path.exists(target_path):
            os.makedirs(target_path)
            self.log(f"创建目标目录: {target_path}")
        
        # 获取选中的文件路径
        selected_items = [self.smart_search_result_listbox.get(i) for i in selected_indices]
        
        self.log(f"开始复制{len(selected_items)}个文件/文件夹到 '{target_path}'")
        success, count = self.ftp2pdm.copy_items_with_manager(selected_items, target_path, overwrite)
        
        if success:
            self.log(f"文件/文件夹复制完成，成功复制了{count}个项目")
            messagebox.showinfo("成功", f"已成功复制{count}个文件/文件夹")
        else:
            self.log("文件/文件夹复制失败")
            messagebox.showwarning("警告", "文件/文件夹复制失败")

def main():
    """主函数"""
    root = tk.Tk()
    app = FTP2PDMGUI(root)
    root.mainloop()

if __name__ == "__main__":
    main()